public class NTMKTAdjustKAResourceController
{
    public Boolean IsEnableForActionButton{get;set;}//按钮是否可用
    public CommonMethod getCommonMethod;
    public String RecordId
   {
       get
       {
           return String.valueOf(System.currentPageReference().getParameters().get('id')).substring(0,15);  
       }
       set;
   }
   public String IsUpdateData
   {
       get
       {
           return System.currentPageReference().getParameters().get('IsUpdateData');
       }
   }
   public Activity_Information__c ActivityInfo{get;set;}
   public List<String> ETColumnList{get;set;}//列
   public List<DynamicColumnEntry> DynamicColumnList{get;set;}//动态列
    public List<AllocationResourceEntry> ResourceEntryList{get;set;}//资源分配列表
    public List< Activity_Target_And_Allocation_Total__c> kaTargetList;//取出KA target列表
    public map<String,DynamicColumnEntry > entryMapList;
    public map<string,Integer> KATargetTotalNumberList;//每个KA的target数
    public Integer OTTargetTotalNumber{get;set;}//OT总的target数 
    
     public NTMKTAdjustKAResourceController(ApexPages.StandardController controller)
     {
         IsEnableForActionButton=true;
         //查询活动状态
         ActivityInfo=[select Activity_Stage__c,name,OwnerId from Activity_Information__c where id=:RecordId];
         if(RecordId!=NULL && (ActivityInfo.Activity_Stage__c=='总部已发起活动' || ActivityInfo.Activity_Stage__c=='活动已取消'))
         {
            IsEnableForActionButton=false;
         }
         if(ActivityInfo.OwnerId!=UserInfo.getUserId())
             IsEnableForActionButton=false;
             
         getCommonMethod=new CommonMethod();
        // if(DynamicColumnList=new List<DynamicColumnEntry>();)
        if(DynamicColumnList==NULL)
            DynamicColumnList=new List<DynamicColumnEntry>();
        else
            DynamicColumnList.clear();
            
         if(ResourceEntryList==NULL)
             ResourceEntryList=new  List<AllocationResourceEntry>();
         else
            ResourceEntryList.clear();
            
            KATargetTotalNumberList=new map<string,Integer>();
             
            ETColumnList=new List<String>();
            Set<String> columnList=new   Set<String>();
             
            //获取所有KA target
             kaTargetList=[select  KAName__c, Type__c,TargetNumber__c from  Activity_Target_And_Allocation_Total__c 
                                   where Activity_Information__c=:RecordId and Type__c='KA'  order by TargetNumber__c desc];
                                   
            decimal allKATarget=0;
           // OTTargetTotalNumber=0;
            for(Activity_Target_And_Allocation_Total__c katarget:kaTargetList)//汇总所有KA的target
            {
                     allKATarget+=katarget.TargetNumber__c;
                     KATargetTotalNumberList.put(katarget.KAName__c,Integer.valueOf(katarget.TargetNumber__c));
            }
                
            List<Resource_Allocation__c> rsList=[select KA_Allocation_Number__c ,Product_Name__r.Name ,Product_Name__r.SKU_Code__c
                                                         from Resource_Allocation__c where  Activity_Information_Name__c=:RecordId  
                                                         and  KA_Allocation_Number__c>0];
                                                         
            List<CityResourceAllcation__c> kaTotalResList=new List<CityResourceAllcation__c>();
            kaTotalResList=[select id,KAName__c,Resource_Allocation__c,ResourceNumber__c from CityResourceAllcation__c where Activity_Information__c=:RecordId and Type__c='KA'];
                                                                     
             entryMapList=new map<String,DynamicColumnEntry >();
             Integer resourceNumber=0;//计算资源数
             entryMapList.clear();
             //动态列
             for(Resource_Allocation__c rs:rsList)
             {
                 resourceNumber=0;
                 if(!columnList.contains(rs.Product_Name__r.Name))
                 {
                     ETColumnList.add(rs.Product_Name__r.Name);
                     columnList.add(rs.Product_Name__r.Name);
                  }   
                 ResourceEntryList.add(new AllocationResourceEntry('',rs.Product_Name__r.SKU_Code__c,rs.Product_Name__r.Name,
                                                                                Integer.valueOf(rs.KA_Allocation_Number__c),0,Integer.valueOf(rs.KA_Allocation_Number__c)));
               }   
               if(ActivityInfo.Activity_Stage__c=='总部已发起活动' || ActivityInfo.Activity_Stage__c=='活动已取消')
               {
                       for(CityResourceAllcation__c kaTotal:kaTotalResList)
                       {
                           CreateKAData(kaTotal.KAName__c,kaTotal.ResourceNumber__c,kaTotal.Resource_Allocation__c);
                       }
               }
               else
               {
                   for(Resource_Allocation__c rs:rsList)
                   {  
                           resourceNumber=0;
                          for(Activity_Target_And_Allocation_Total__c tar:kaTargetList)
                          {
                                  decimal numValue=(tar.TargetNumber__c/allKATarget)*rs.KA_Allocation_Number__c;
                                  resourceNumber+=numValue.round().intValue();
                                  CreateKAData(tar.KAName__c,numValue,rs.id);
                              
                          }
                             //分少了,分给占比大的KA
                          if(resourceNumber<rs.KA_Allocation_Number__c)
                          {
                              Integer num=Integer.valueOf(rs.KA_Allocation_Number__c-resourceNumber);
                              AscAdjustData(num,rs.id);
                          }        
                          else if(resourceNumber>rs.KA_Allocation_Number__c)//分多了
                          {
                              Integer num=Integer.valueOf(resourceNumber-rs.KA_Allocation_Number__c);
                              DescAdjustData(num,rs.Id);
                          }
                 }    
             }
              DynamicColumnList=entryMapList.values(); 
        //  LoadKAResource();//加载KA资源数
     }
     
     
     public void CreateKAData(string kaName,decimal numValue,string resourceId)
     {
         if(entryMapList.containsKey(kaName))
          {
                   DynamicColumnEntry entry=(DynamicColumnEntry )entryMapList.get(kaName);
                   if(entry.Resource2==-1)
                   {
                       entry.Resource2=numValue.round().intValue();
                       entry.resourceId2=resourceId;
                   }
                  else  if(entry.Resource3==-1)
                  {
                       entry.Resource3=numValue.round().intValue();
                       entry.resourceId3=resourceId;
                  }
                  else   if(entry.Resource4==-1)
                  {
                       entry.Resource4=numValue.round().intValue();
                       entry.resourceId4=resourceId;
                  }
                  else    if(entry.Resource5==-1)
                  {
                       entry.Resource5=numValue.round().intValue();
                       entry.resourceId5=resourceId;
                  }
                   entryMapList.put(kaName,entry);
          }
          else
          {
              
              DynamicColumnEntry entry=new DynamicColumnEntry();
              entry.OutletName=kaName;
              entry.Resource1=numValue.round().intValue();
              entry.resourceId1=resourceId;
           
              entry.Resource2=-1;
              entry.Resource3=-1;
              entry.Resource4=-1;
              entry.Resource5=-1;
              entryMapList.put(kaName,entry);
          }
     }
      public void AscAdjustData(Integer num,string resourceId)
     {
          for(Integer i=0;i<kaTargetList.size();i++)
          {
              DynamicColumnEntry dce=entryMapList.get(kaTargetList[i].KAName__c);
              if(dce!=NULL)
              {
                  if(dce.resourceId1==resourceId)
                  {
                          dce.Resource1+=num;
                          entryMapList.put(kaTargetList[i].KAName__c,dce);
                          break;
                  }
                  if(dce.resourceId2==resourceId)
                  {
                          dce.Resource2+=num;
                          entryMapList.put(kaTargetList[i].KAName__c,dce);
                          break;
                  }
                   if(dce.resourceId3==resourceId)
                  {
                          dce.Resource3+=num;
                          entryMapList.put(kaTargetList[i].KAName__c,dce);
                          break;
                  }
                   if(dce.resourceId4==resourceId)
                  {
                          dce.Resource4+=num;
                          entryMapList.put(kaTargetList[i].KAName__c,dce);
                          break;
                  }
                  if(dce.resourceId5==resourceId)
                  {
                          dce.Resource5+=num;
                          entryMapList.put(kaTargetList[i].KAName__c,dce);
                          break;
                  }
               }
          }
     }
     
     public void DescAdjustData(Integer num,string resourceId)
     {
          for(Integer i=kaTargetList.size()-1;i>=0;i--)
          {
              DynamicColumnEntry dce=entryMapList.get(kaTargetList[i].KAName__c);
              if(dce!=NULL)
              {
                  if(dce.resourceId1==resourceId)
                  {
                      if(dce.Resource1>=num)
                      {
                          dce.Resource1-=num;
                          entryMapList.put(kaTargetList[i].KAName__c,dce);
                          break;
                      }
                  }
                  if(dce.resourceId2==resourceId)
                  {
                      if(dce.Resource2>=num)
                      {
                          dce.Resource2-=num;
                          entryMapList.put(kaTargetList[i].KAName__c,dce);
                          break;
                      }
                  }
                   if(dce.resourceId3==resourceId)
                  {
                      if(dce.Resource3>=num)
                      {
                          dce.Resource3-=num;
                          entryMapList.put(kaTargetList[i].KAName__c,dce);
                          break;
                      }
                  }
                   if(dce.resourceId4==resourceId)
                  {
                     if(dce.Resource4>=num)
                     {
                          dce.Resource4-=num;
                          entryMapList.put(kaTargetList[i].KAName__c,dce);
                          break;
                      }
                  }
                  if(dce.resourceId5==resourceId)
                  {
                      if(dce.Resource5>=num)
                      {
                          dce.Resource5-=num;
                          entryMapList.put(kaTargetList[i].KAName__c,dce);
                          break;
                      }
                  }
               }
          }
     }
        //保存数据
     public PageReference SaveData()
     {
         SaveToDataBase(false);
         pageReference pr = new pageReference('/'+ActivityInfo.id);     
          pr.setredirect(true);   
          return pr;
     //  return null;
     }
     public PageReference  SubmitData()
     {
          ActivityInfo.Activity_Stage__c='总部已发起活动';
          update ActivityInfo;
         SaveToDataBase(true);
         IsEnableForActionButton=false;
         
         //发送给KA
        String BodyString='总部已发起【'+ActivityInfo.Name+'】活动.请登陆凤凰系统进行资源调整.谢谢!';
        String subject=ActivityInfo.Name+'活动已发起';
        EmailHander.SendMail(BodyString,getCommonMethod.getUserEmailAddress('KAM',RecordId),subject,'',null);
          
          pageReference pr = new pageReference('/'+ActivityInfo.id);     
          pr.setredirect(true);   
          return pr;
     }
     //上一页
     public PageReference PreviousStep()
     {
          pageReference pr = new pageReference('/apex/NTMKTStep2AddParticipator?id='+ActivityInfo.id);     
           pr.setredirect(true);   
           return pr;
     }
     public void SaveToDataBase(boolean isSubmit)
     {
         List<CityResourceAllcation__c> KAList=new List<CityResourceAllcation__c>();
        for(DynamicColumnEntry entry:DynamicColumnList)
        {
            if(entry.Resource1>=0)
               KAList.add(CreateKATotal(entry.OutletName,entry.Resource1,entry.resourceId1));
            if(entry.Resource2>=0)
              KAList.add(CreateKATotal(entry.OutletName,entry.Resource2,entry.resourceId2));
           if(entry.Resource3>=0)
              KAList.add(CreateKATotal(entry.OutletName,entry.Resource3,entry.resourceId3));
           if(entry.Resource4>=0)
              KAList.add(CreateKATotal(entry.OutletName,entry.Resource4,entry.resourceId4));
            if(entry.Resource5>=0)
              KAList.add(CreateKATotal(entry.OutletName,entry.Resource5,entry.resourceId5));
        }
        delete [select id from CityResourceAllcation__c where Activity_Information__c=:RecordId];
        insert KAList;
        
      if(isSubmit)
     {
             List<CityResourceAllcation__c> kaResourceList=new List<CityResourceAllcation__c>();
             map<string,string> subregionList=new map<string,string>();//保存每个城市对应的subregion
             map<string,string> regionList=new map<string,string>();//保存每个城市对应的region
            map<string,Integer> otCityList=new map<string,Integer>();//OT城市的target列表
            map<string,map<string,double>> kaCityList=new  map<string,map<string,double>>();//KA城市的target列表,保存某个ＫＡ对应的城市target
            double otTotal=0;
            map<string,double> KATargetList=new map<string,double>();
            map<string,Integer> TotalKAOutletNumberList=new  map<string,Integer>();//保存KA的门店数
            //汇总ＯＴ和ＫＡ
            for(Activity_Target_And_Allocation_Total__c ataat:[select KAName__c,CityName__c,SubRegion__c,Region__c,TargetNumber__c,Type__c,OutletNumber__c
                                                                                    from Activity_Target_And_Allocation_Total__c
                                                                                    where  Activity_Information__c=:RecordId and (Type__c='OTCity' or Type__c='KACity')])
            {
                regionList.put(ataat.CityName__c,ataat.Region__c);
                subregionList.put(ataat.CityName__c,ataat.SubRegion__c);
                if(ataat.Type__c=='OTCity')
                {
                    otCityList.put(ataat.CityName__c,Integer.valueOf(ataat.TargetNumber__c));
                    otTotal+=ataat.TargetNumber__c;
                }
                else
                {
                    //汇总KA每个城市的门店数
                    if(!TotalKAOutletNumberList.containsKey(ataat.KAName__c+ataat.CityName__c))
                    {
                        TotalKAOutletNumberList.put(ataat.KAName__c+ataat.CityName__c,Integer.valueOf(ataat.OutletNumber__c));
                    }
                  
                    //汇总每个ＫＡ每个城市的target数
                    if(kaCityList.containsKey(ataat.KAName__c))
                    {
                        map<string,double> cityList=kaCityList.get(ataat.KAName__c);
                        cityList.put(ataat.CityName__c,ataat.TargetNumber__c);
                        kaCityList.put(ataat.KAName__c,cityList);
                    }
                    else
                    {
                        map<string,double> cityList=new map<string,double>();
                        cityList.put(ataat.CityName__c,ataat.TargetNumber__c);
                        kaCityList.put(ataat.KAName__c,cityList);
                    }
                    //by ka汇总target
                    if(KATargetList.containsKey(ataat.KAName__c))
                    {
                        double num=KATargetList.get(ataat.KAName__c)+ataat.TargetNumber__c;
                        KATargetList.put(ataat.KAName__c,num);
                    }
                    else
                    {
                        KATargetList.put(ataat.KAName__c,ataat.TargetNumber__c);
                    }
                }
            }
         
            //按城市分配资源
             List<Resource_Allocation__c> raList=[select id,Product_Name__r.Pack_Size_C__c,OT_Allocation_Number__c
                                                                      from Resource_Allocation__c 
                                                                      where Activity_Information_Name__c=:RecordId and OT_Allocation_Number__c>0];
             
             //OT分配
             Integer sumOTTotal=0;
             List<CityResourceAllcation__c> CityAllocationList=new List<CityResourceAllcation__c>();
             for(Resource_Allocation__c ra:raList)
             {
                 CityAllocationList.clear();
                 sumOTTotal=0;
                 for(string str:otCityList.keySet())
                 {
                     Integer cityNum=Integer.valueOf(otCityList.get(str));
                     double resultNum=cityNum/otTotal*ra.OT_Allocation_Number__c;
                     
                     CityResourceAllcation__c kaRes=new CityResourceAllcation__c();
                     kaRes.Activity_Information__c=RecordId;
                     kaRes.CityName__c=str;
                     kaRes.Resource_Allocation__c=ra.id;
                     kaRes.ResourceNumber__c=resultNum.round();
                     kaRes.Type__c='OTCity';
                     kaRes.Region__c=regionList.get(kaRes.CityName__c);
                     kaRes.SubRegion__c=subregionList.get(kaRes.CityName__c);
                     CityAllocationList.add(kaRes);
                     sumOTTotal+=Integer.valueOf(resultNum.round());
                 }
                 if(sumOTTotal!=ra.OT_Allocation_Number__c)
                     kaResourceList.addAll(getCommonMethod.ReturnCityAdjustList(CityAllocationList,sumOTTotal,Integer.valueOf(ra.OT_Allocation_Number__c)));
                 else
                     kaResourceList.addAll(CityAllocationList); 
             }
         
             //by city 分配KA资源
             for(CityResourceAllcation__c ktra:KAList)
             {
                 CityAllocationList.clear();
                 sumOTTotal=0;
                 map<string,double> cityList=kaCityList.get(ktra.KAName__c);//取出某个KA的所有的城市target数
                 double target=KATargetList.get(ktra.KAName__c);//取出ＫＡ target总数
                 if(cityList!=NULL)
                 {
                     for(string str:cityList.keySet())//取出城市列表
                     {
                         double num=cityList.get(str);//取出target
                         
                         double resultNum=num/target*ktra.ResourceNumber__c;
                         CityResourceAllcation__c kaRes=new CityResourceAllcation__c();
                         kaRes.Activity_Information__c=RecordId;
                         kaRes.CityName__c=str;
                         kaRes.KAName__c=ktra.KAName__c;
                         kaRes.OutletNumber__c=TotalKAOutletNumberList.get(ktra.KAName__c+str);
                         kaRes.Resource_Allocation__c=ktra.Resource_Allocation__c;
                         kaRes.ResourceNumber__c=resultNum.round();
                         kaRes.Type__c='KACity';
                         kaRes.Region__c=regionList.get(kaRes.CityName__c);
                         kaRes.SubRegion__c=subregionList.get(kaRes.CityName__c);
                         CityAllocationList.add(kaRes);
                         sumOTTotal+=Integer.valueOf(resultNum.round());
                     }
                     if(sumOTTotal!=ktra.ResourceNumber__c)
                         kaResourceList.addAll(getCommonMethod.ReturnCityAdjustList(CityAllocationList,sumOTTotal,Integer.valueOf(ktra.ResourceNumber__c)));
                     else
                         kaResourceList.addAll(CityAllocationList);     
                 }
             }
             insert kaResourceList;
             
             //获取OT竞品费用类型
            List<Activity_Competition_Brand_Information__c> competitionList=[select id from Activity_Competition_Brand_Information__c where Activity_Information__c=:RecordId and Type__c='OT'];
            
             map<string,List<CityResourceAllcation__c>> KACityResourceList=new map<string,List<CityResourceAllcation__c>>();
             map<string,List<CityResourceAllcation__c>> OTCityResourceList=new map<string,List<CityResourceAllcation__c>>();
            for(CityResourceAllcation__c ktra:[select KAName__c,CityName__c,PackSize__c,Resource_Allocation__c,ResourceNumber__c,Type__c 
                                                            from CityResourceAllcation__c where Activity_Information__c=:RecordId and Type__c!='KA'])
            {
                if(ktra.Type__c=='KACity')
                {
                    if(KACityResourceList.containsKey(ktra.KAName__c+ktra.CityName__c))
                    {
                        List<CityResourceAllcation__c> cityList=KACityResourceList.get(ktra.KAName__c+ktra.CityName__c);
                        cityList.add(ktra);
                        KACityResourceList.put(ktra.KAName__c+ktra.CityName__c,cityList);
                    }
                    else
                    {
                        List<CityResourceAllcation__c> cityList=new List<CityResourceAllcation__c>();
                        cityList.add(ktra);
                        KACityResourceList.put(ktra.KAName__c+ktra.CityName__c,cityList);
                    }
                 }
                if(ktra.Type__c=='OTCity')
                {
                     if(OTCityResourceList.containsKey(ktra.CityName__c))
                     {
                         List<CityResourceAllcation__c> cityList=OTCityResourceList.get(ktra.CityName__c);
                        cityList.add(ktra);
                        OTCityResourceList.put(ktra.CityName__c,cityList);
                     }
                     else
                     {
                        List<CityResourceAllcation__c> cityList=new List<CityResourceAllcation__c>();
                        cityList.add(ktra);
                        OTCityResourceList.put(ktra.CityName__c,cityList);
                    }
                }
            }
            delete [select id from Resource_Allocation_Detail__c where ActivityId__c=:RecordId];
            delete [select id from Activity_Competition_Brand_Detail__c where ActivityId__c=:RecordId];
            
             CreateResourceAllcationDetail createResource=new CreateResourceAllcationDetail(RecordId,competitionList,kaCityList,otCityList,KACityResourceList,OTCityResourceList);
             Database.executeBatch(createResource);
          
            //删除竞品明细
          /*  delete [select id from Activity_Competition_Brand_Detail__c where ActivityId__c=:RecordId];
            //查询KA资源数
            List< CityResourceAllcation__c> kaTotalResourceList=new List< CityResourceAllcation__c>();
            kaTotalResourceList=[select id,KAName__c,Resource_Allocation__c,ResourceNumber__c,PackSize__c from CityResourceAllcation__c where Activity_Information__c=:RecordId];
           //获取资源分配信息
            List<Resource_Allocation__c> raList=[select id,Product_Name__r.Pack_Size_C__c,OT_Allocation_Number__c 
                                                                      from Resource_Allocation__c 
                                                                      where Activity_Information_Name__c=:RecordId and OT_Allocation_Number__c>0];
            //获取所有OT target
            Integer OTTotalTarget=0;
            for(Activity_Target_And_Allocation_Total__c otTarget:[select TargetNumber__c from  Activity_Target_And_Allocation_Total__c 
                                                                                               where Activity_Information__c=:RecordId and Type__c='Area' ])
            {
                OTTotalTarget+=Integer.valueOf(otTarget.TargetNumber__c);
            }
            
            //参数：raList(OT的资源信息);kaTotalResourceList(KA分配信息);RecordId(活动ID);OTTotalTarget(OT所有参与者的target总数);KATargetTotalNumberList(每个KA的target总数);competitionList(OT竞品类型)
            CreateResourceAllcationDetail createResource=new CreateResourceAllcationDetail(raList,kaTotalResourceList,RecordId,OTTotalTarget,KATargetTotalNumberList,competitionList);
            Database.executeBatch(createResource);*/
        }
     }
     public CityResourceAllcation__c CreateKATotal(string kaName,Integer resourceNum,string resourceId)
     {
         CityResourceAllcation__c ka=new CityResourceAllcation__c();
        ka.Activity_Information__c=RecordId;
        ka.KAName__c=kaName;
        ka.Resource_Allocation__c=resourceId;
        ka.ResourceNumber__c=resourceNum;
        ka.Type__c='KA';
        return ka;
     }
}